<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2020/6/26
 * Time: 4:05 PM
 */

namespace app\api\http\exceptions;


use think\db\exception\DbException;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use think\exception\Handle;

/**
 * 异常处理接管
 * Class ApiHandler
 * @package app\Exceptions
 */
class ApiHandler extends Handle
{
    use ResponseJson;

    protected $httpCode = 500;

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        $message = '';
        $status = ApiErr::API_UNKNOWN_ERROR[0];
        $this->isJson = true;
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        }
        //校验异常
        if ($e instanceof ValidateException) {
            return $this->jsonErrResponse($e->getCode(), $e->getError(), [], 422);
        } elseif ($e instanceof HttpException) {
            $message = $e->getMessage();
            $status = $e->getCode();
            $this->httpCode = 404;
        } else if ($e instanceof DbException) {
            $status = ApiErr::API_DB_ERROR[0];
            $message = ApiErr::API_DB_ERROR[1] . ':' . $e->getMessage();
        } else if ($e instanceof \Exception) {
            $status = $e->getCode();
            $message = $e->getMessage();
        } else {
            $status = $e->getCode();
            if (!$status || $status < 0) {
                $status = ApiErr::API_UNKNOWN_ERROR[0];
            }
            $message = empty($e->getMessage()) ? ApiErr::API_UNKNOWN_ERROR[1] : $e->getMessage();
        }

        // 添加自定义异常处理机制
        if (method_exists($e, 'getStatusCode')) {
            $this->httpCode = $e->getStatusCode();
        }
        return $this->jsonErrResponse($status, $message, [], $this->httpCode);
    }

}